<?php
namespace App\Services\Traits;

use Symfony\Component\HttpFoundation\Response as FoundationResponse;

trait ApiResponse
{
    /**
     * 成功返回
     * @param $data
     * @param string $status
     * @return \Illuminate\Http\Response
     */
    public function success($data = [])
    {
        $res = [
            'message'   => 'success',
            'code'      => FoundationResponse::HTTP_OK,
            'data'      => $data
        ];
        return $this->response($res);
    }

    /**
     * 失败返回 HTTP_CODE 为 200  返回信息里可以自定义code
     * @param $message
     * @param int $code
     * @param string $status
     * @return \Illuminate\Http\Response
     */
    public function failed($message , $code = FoundationResponse::HTTP_BAD_REQUEST)
    {
        $res = [
            'message'   => $message,
            'code'      => $code,
        ];
        return $this->response($res , FoundationResponse::HTTP_OK);
    }

    /**
     * 失败返回  HTTP_CODE 与 返回信息 $code 一直
     * @param $message
     * @param int $code
     * @param string $status
     * @return \Illuminate\Http\Response
     */
    public function error($message)
    {
        $res = [
            'message'   => $message,
            'code'      => FoundationResponse::HTTP_BAD_REQUEST,
        ];
        return $this->response($res , FoundationResponse::HTTP_BAD_REQUEST);
    }
    /**
     * @param string $message
     * @return \Illuminate\Http\Response
     */
    public function internalError($message = "Internal Error!")
    {
        return $this->failed($message, FoundationResponse::HTTP_INTERNAL_SERVER_ERROR);
    }

    /**
     * @param string $message
     * @return \Illuminate\Http\Response
     */
    public function created($message = "created")
    {
        return $this->setStatusCode(FoundationResponse::HTTP_CREATED)
            ->message($message);
    }
    /**
     * @param string $message
     * @return \Illuminate\Http\Response
     */
    public function notFound($message = 'Not Found!')
    {
        return $this->failed($message, FoundationResponse::HTTP_NOT_FOUND);
    }
    /**
     * @param string $message
     * @return \Illuminate\Http\Response
     */
    public function unauthorized($message = 'Unauthorized!')
    {
        return $this->failed($message, FoundationResponse::HTTP_UNAUTHORIZED);
    }
    /**
     * @param [type] $data
     * @param [type] $code
     * @param array $header
     * @return void
     */
    public function response($data , $code = FoundationResponse::HTTP_OK , $header = []){
        $content = preg_replace(
            [
                '/":null/',
                '/":true/',
                '/":false/',
            ],
            [
                '":""',
                '":1',
                '":0',
            ],
            json_encode($data, JSON_UNESCAPED_UNICODE)
        );
        return response($content , $code , $header);
    }
}
